#include "VisionMainWnd.h"
#include <QtWidgets/QApplication>

//#include <QApplication>
#include <winsock2.h>
#include <dbghelp.h>
#include <windows.h>
#include <winnt.h>
#include <QMessageBox>
#include <QString>
#include <QTime>
#include <QFile>
#include <QSplashscreen>

#include "DarkStyle.h"
#include "framelesswindow.h"

#pragma comment(lib, "dbghelp.lib")


LONG ExceptionCapture(EXCEPTION_POINTERS* pException)
{
    //当前时间串
    const int TIMESTRLEN = 32;
    WCHAR timeStr[TIMESTRLEN];
    SYSTEMTIME time;
    GetLocalTime(&time);
    swprintf_s(timeStr, TIMESTRLEN, L"%4d%02d%02d%02d%02d%02d", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
    WCHAR strname[MAX_PATH];
    swprintf_s(strname, MAX_PATH, L"application_%s.dmp", timeStr);

    //创建 Dump 文件
    HANDLE hDumpFile = CreateFile(strname, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
    if (hDumpFile != INVALID_HANDLE_VALUE)
    {
        //Dump信息
        MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
        dumpInfo.ExceptionPointers = pException;
        dumpInfo.ThreadId = GetCurrentThreadId();
        dumpInfo.ClientPointers = TRUE;
        //写入Dump文件内容
        MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, nullptr, nullptr);

        CloseHandle(hDumpFile);
    }

    //完成一些数据保存工作
    //.....

    //弹出错误对话框并退出程序
    QMessageBox::critical(nullptr, "错误提示", QString("当前程序遇到异常.\n  异常文件:%1").arg(QString::fromWCharArray(strname)), QMessageBox::Ok, QMessageBox::Ok);
    return EXCEPTION_EXECUTE_HANDLER;
}


int main(int argc, char *argv[])
{
    // 注册异常处理：崩溃时导出dump文件用于诊断
    SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ExceptionCapture);


    QApplication a(argc, argv);

    HANDLE hMutex = CreateMutex(nullptr, TRUE, (LPCWSTR)qApp->applicationName().toStdWString().c_str());
    if (GetLastError() == ERROR_ALREADY_EXISTS) {
        QMessageBox::warning(nullptr, "Error", "An instance of the application is already running.");
        CloseHandle(hMutex);
        hMutex = NULL;
        return 1;
    }

    // splash加载
    QSplashScreen startSplash(QPixmap("startSplash.png"));
    startSplash.setDisabled(true);
    startSplash.setFont(QFont("宋体", 16, QFont::Bold));
    startSplash.showMessage(QObject::tr("安川机器人抓取系统正在启动......"),
        Qt::AlignLeft | Qt::AlignBottom, Qt::green);
    startSplash.show();

    QString strStyleSheet = "";
    QFile file("bluewhite-style.qss");
    if (file.open(QFile::ReadOnly))
    {
        strStyleSheet = QLatin1String(file.readAll());
    }
    a.setStyleSheet(strStyleSheet);
    file.close();

    VisionMainWnd* mainWindow = new VisionMainWnd;

    mainWindow->showMaximized();
    startSplash.finish(mainWindow);

    a.exec();

    CloseHandle(hMutex);
    hMutex = NULL;
    return 0;
}
